package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //添加分类
    @PostMapping
    public R addCategory(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加分类成功");
    }

    //分页查询
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize){
        Page<Category> page1 = new Page(page,pageSize);
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByDesc(Category::getSort);
        categoryService.page(page1,lambdaQueryWrapper);
        return R.success(page1);
    }

    //删除分类
    @DeleteMapping
    public R<String> deleteCategory(Long id){

        /*categoryService.removeById(id);
        return R.success("删除成功");*/

        boolean flag = categoryService.remove(id);
        if (flag){
            categoryService.removeById(id);
            return R.success("删除成功");
        }
        return R.error("删除失败");
    }

    //修改菜品分类
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R list(Category category){
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(category.getType() !=null,Category::getType,category.getType());
        lambdaQueryWrapper.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lambdaQueryWrapper);
        return R.success(list);
    }
}
